package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.dto.IotMsgNotifyData;
import com.zzyl.nursing.dto.IotMsgService;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Map;

/**
 * 设备数据Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-25
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }
    @Autowired
    private IDeviceService deviceService;

    @Override
    public void saveDeviceData(IotMsgNotifyData notifyData) {
        //从中获取iotid查询数据库中是否有设备
        String deviceId = notifyData.getHeader().getDeviceId();
        Device one = deviceService.lambdaQuery().eq(Device::getIotId, deviceId).one();
        if (one==null){
            throw new BaseException("数据库中无此设备");
        }
        //获取serviceproperties插入
        List<IotMsgService> services = notifyData.getBody().getServices();
        if (CollectionUtils.isEmpty(services)){
            throw new BaseException("云端数据为空");
        }
        ArrayList<DeviceData> deviceData = new ArrayList<>();
        services.forEach(x->{
            String eventTime = x.getEventTime();
            LocalDateTime alarmTime = OffsetDateTime.parse(eventTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            Map<String, Object> properties = x.getProperties();

            properties.forEach((k,v)->{
                DeviceData bean = BeanUtil.toBean(one, DeviceData.class);
                bean.setFunctionId(k);
                bean.setDataValue(String.valueOf(v));
                bean.setAlarmTime(alarmTime);
                bean.setId(null);
                bean.setCreateBy(null);
                bean.setCreateTime(null);
                bean.setUpdateBy(null);
                bean.setUpdateTime(null);
                deviceData.add(bean);
            });
        }

        );
        this.saveBatch(deviceData);
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_DATA_LATEST,deviceId, JSONUtil.toJsonStr(deviceData));

    }

    /**
     * 设备物模型上报数据分页
     *
     * @param dto
     * @return
     */
    @Override
    public List<DeviceData> getPage(DeviceDataPageReqDto dto) {
        List<DeviceData> list = this.lambdaQuery()
                .eq(StrUtil.isNotBlank(dto.getDeviceId()), DeviceData::getIotId, dto.getDeviceId())
                .eq(StrUtil.isNotBlank(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                .eq(StrUtil.isNotBlank(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .between(dto.getStartTime() != null && dto.getEndTime() != null, DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime())
                .orderByDesc(DeviceData::getAlarmTime).list();


        return list;
    }
}
